<template>
  <div class="api-status-checker" v-if="isDev">
    <el-card class="status-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>🔗 API连接状态</span>
          <el-button @click="checkAllApis" :loading="checking" size="small" type="primary">
            检查连接
          </el-button>
        </div>
      </template>
      
      <div class="status-list">
        <div 
          v-for="api in apiStatus" 
          :key="api.name"
          class="status-item"
          :class="api.status"
        >
          <div class="status-info">
            <span class="status-icon">
              <el-icon v-if="api.status === 'success'"><SuccessFilled /></el-icon>
              <el-icon v-else-if="api.status === 'error'"><CircleCloseFilled /></el-icon>
              <el-icon v-else><Loading /></el-icon>
            </span>
            <span class="status-name">{{ api.name }}</span>
            <span class="status-url">{{ api.url }}</span>
          </div>
          <div class="status-result">
            <span class="status-time" v-if="api.responseTime">{{ api.responseTime }}ms</span>
            <span class="status-message">{{ api.message }}</span>
          </div>
        </div>
      </div>
      
      <div class="status-summary" v-if="lastCheckTime">
        <p>上次检查: {{ formatTime(lastCheckTime) }}</p>
        <p>成功率: {{ successRate }}%</p>
      </div>
      
      <div class="quick-actions">
        <el-button @click="runApiTests" size="small" type="success">
          运行API测试
        </el-button>
        <el-button @click="openBackendConsole" size="small" type="info">
          后端控制台
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { SuccessFilled, CircleCloseFilled, Loading } from '@element-plus/icons-vue'
import { authApi, serviceApi, merchantApi, searchApi } from '@/services/api'
import { apiTester } from '@/utils/apiTester'

// 开发环境检查
const isDev = import.meta.env.DEV

// 响应式数据
const checking = ref(false)
const lastCheckTime = ref(null)

// API状态列表
const apiStatus = ref([
  {
    name: '认证服务',
    url: '/api/auth/me',
    status: 'pending',
    message: '等待检查',
    responseTime: null,
    check: () => authApi.getUserInfo()
  },
  {
    name: '服务分类',
    url: '/api/services/categories',
    status: 'pending',
    message: '等待检查',
    responseTime: null,
    check: () => serviceApi.getServiceCategories()
  },
  {
    name: '商家列表',
    url: '/api/merchants',
    status: 'pending',
    message: '等待检查',
    responseTime: null,
    check: () => merchantApi.getMerchantList({ page: 0, size: 1 })
  },
  {
    name: '搜索推荐',
    url: '/api/search/recommendations',
    status: 'pending',
    message: '等待检查',
    responseTime: null,
    check: () => searchApi.getRecommendations()
  }
])

// 计算成功率
const successRate = computed(() => {
  const total = apiStatus.value.length
  const success = apiStatus.value.filter(api => api.status === 'success').length
  return total > 0 ? Math.round((success / total) * 100) : 0
})

// 检查单个API
const checkSingleApi = async (api) => {
  const startTime = Date.now()
  api.status = 'checking'
  api.message = '检查中...'
  
  try {
    await api.check()
    api.status = 'success'
    api.message = '连接正常'
    api.responseTime = Date.now() - startTime
  } catch (error) {
    api.status = 'error'
    api.responseTime = Date.now() - startTime
    
    if (error.code === 'ECONNREFUSED' || error.message.includes('Network Error')) {
      api.message = '后端服务未启动'
    } else if (error.response?.status === 401) {
      api.message = '需要登录认证'
      api.status = 'warning'
    } else if (error.response?.status === 404) {
      api.message = '接口不存在'
    } else {
      api.message = error.message || '连接失败'
    }
  }
}

// 检查所有API
const checkAllApis = async () => {
  if (checking.value) return
  
  checking.value = true
  lastCheckTime.value = new Date()
  
  try {
    // 并发检查所有API
    await Promise.all(apiStatus.value.map(checkSingleApi))
    
    const successCount = apiStatus.value.filter(api => api.status === 'success').length
    const totalCount = apiStatus.value.length
    
    if (successCount === totalCount) {
      ElMessage.success(`所有API连接正常 (${successCount}/${totalCount})`)
    } else if (successCount > 0) {
      ElMessage.warning(`部分API连接正常 (${successCount}/${totalCount})`)
    } else {
      ElMessage.error('所有API连接失败，请检查后端服务')
    }
    
  } catch (error) {
    console.error('API检查异常:', error)
    ElMessage.error('API检查过程中发生异常')
  } finally {
    checking.value = false
  }
}

// 运行API测试
const runApiTests = async () => {
  try {
    ElMessage.info('开始运行API测试...')
    const results = await apiTester.runAllTests()
    
    const successCount = results.filter(r => r.status === 'success').length
    const totalCount = results.length
    
    if (successCount === totalCount) {
      ElMessage.success(`API测试全部通过 (${successCount}/${totalCount})`)
    } else {
      ElMessage.warning(`API测试部分通过 (${successCount}/${totalCount})`)
    }
    
    console.log('📊 详细测试结果请查看控制台')
  } catch (error) {
    console.error('API测试异常:', error)
    ElMessage.error('API测试过程中发生异常')
  }
}

// 打开后端控制台
const openBackendConsole = () => {
  window.open('http://localhost:8080/h2-console', '_blank')
}

// 格式化时间
const formatTime = (date) => {
  return date.toLocaleTimeString('zh-CN')
}

// 组件挂载时自动检查
onMounted(() => {
  if (isDev) {
    // 延迟1秒后自动检查，避免页面加载时的干扰
    setTimeout(checkAllApis, 1000)
  }
})
</script>

<style scoped>
.api-status-checker {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 400px;
  z-index: 9999;
}

.status-card {
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.status-list {
  margin-bottom: 16px;
}

.status-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.status-item:last-child {
  border-bottom: none;
}

.status-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.status-icon {
  margin-right: 8px;
  font-size: 16px;
}

.status-item.success .status-icon {
  color: #67c23a;
}

.status-item.error .status-icon {
  color: #f56c6c;
}

.status-item.warning .status-icon {
  color: #e6a23c;
}

.status-item.checking .status-icon {
  color: #409eff;
}

.status-name {
  font-weight: 500;
  margin-right: 8px;
  min-width: 60px;
}

.status-url {
  font-size: 12px;
  color: #909399;
  font-family: monospace;
}

.status-result {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  font-size: 12px;
}

.status-time {
  color: #67c23a;
  font-weight: 500;
}

.status-message {
  color: #606266;
  margin-top: 2px;
}

.status-item.error .status-message {
  color: #f56c6c;
}

.status-item.warning .status-message {
  color: #e6a23c;
}

.status-summary {
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  font-size: 12px;
  color: #909399;
}

.status-summary p {
  margin: 4px 0;
}

.quick-actions {
  display: flex;
  gap: 8px;
}

.quick-actions .el-button {
  flex: 1;
}
</style>
